package com.xneure.code;

import java.io.IOException;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.xneure.code.intf.CacheEvent;
import com.xneure.code.plantask.CountTask;
import com.xneure.code.plantask.TimerEvent;

public class CacheMap<K,V>extends AbstractMap<K,V> implements Map<K,V>,Cloneable,Serializable{
	private static final long serialVersionUID = 7413868007493782653L;
	static final int DEFAULT_INITIAL_CAPACITY = 16;
	static final int MAXIMUM_CAPACITY = 1 << 30;
	static final float DEFAULT_LOAD_FACTOR = 0.75f;
	transient Entry<K,V>[] table;
	transient int size;
	private CacheEvent<K,V> call = new CacheEvent<K,V>();
	int threshold;
	final float loadFactor;
	private CountTask task;

	@SuppressWarnings("unchecked")
	public CacheMap(int initialCapacity,float loadFactor){
		if(initialCapacity < 0)
			throw new IllegalArgumentException("初始容量不能为负数: " + initialCapacity);
		if(initialCapacity > MAXIMUM_CAPACITY)
			initialCapacity = MAXIMUM_CAPACITY;
		if(loadFactor <= 0 || Float.isNaN(loadFactor))
			throw new IllegalArgumentException("扩充容量大小错误: " + loadFactor);
		int capacity = 1;
		while(capacity < initialCapacity)
			capacity <<= 1;
		this.loadFactor = loadFactor;
		threshold = (int)(capacity * loadFactor);
		table = new Entry[capacity];
		init(true);
	}

	public CacheMap(int initialCapacity){
		this(initialCapacity,DEFAULT_LOAD_FACTOR);
	}

	@SuppressWarnings("unchecked")
	public CacheMap(){
		this.loadFactor = DEFAULT_LOAD_FACTOR;
		threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
		table = new Entry[DEFAULT_INITIAL_CAPACITY];
		init(true);
	}

	public CacheMap(Map<? extends K,? extends V> m){
		this(Math.max((int)(m.size() / DEFAULT_LOAD_FACTOR) + 1,DEFAULT_INITIAL_CAPACITY),DEFAULT_LOAD_FACTOR);
		putAllForCreate(m);
	}

	void init(boolean startTime){
		task = new CountTask(-1);
		task.setRunEvent(new TimerEvent(){
			@Override
			public void tick(){
				for(int i = 0;i < table.length;i++){
					if(null != table[i] && table[i].check() == false){
						table[i] = null;
						size--;
					}
				}
			}
		});
		if(startTime){
			setCheckTime(60000);
		}
	}

	public void setCheckTime(long time){
		task.setInterval(time);
		task.start();
	}

	public void stopRefresh(){
		task.end();
	}

	static int hash(int h){
		h ^= (h >>> 20) ^ (h >>> 12);
		return h ^ (h >>> 7) ^ (h >>> 4);
	}

	static int indexFor(int h,int length){
		return h & (length - 1);
	}

	public int size(){
		return size;
	}

	public boolean isEmpty(){
		return size == 0;
	}

	public V get(Object key){
		if(key == null)
			return getForNullKey();
		int hash = hash(key.hashCode());
		for(Entry<K,V> e = table[indexFor(hash,table.length)];e != null;e = e.next){
			Object k;
			if(e.hash == hash && ((k = e.key) == key || key.equals(k))){
				if(e.check()){
					e.recordAccess(this);
					return e.value;
				}else{
					remove(key);
					return null;
				}
			}
		}
		return null;
	}

	private V getForNullKey(){
		for(Entry<K,V> e = table[0];e != null;e = e.next){
			if(e.key == null){
				if(e.check()){
					e.recordAccess(this);
					return e.value;
				}else{
					remove(null);
					return null;
				}
			}
		}
		return null;
	}

	public boolean containsKey(Object key){
		return getEntry(key) != null;
	}

	final Entry<K,V> getEntry(Object key){
		int hash = (key == null) ? 0 : hash(key.hashCode());
		for(Entry<K,V> e = table[indexFor(hash,table.length)];e != null;e = e.next){
			Object k;
			if(e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))){
				if(e.check()){
					return e;
				}else{
					remove(key);
					return null;
				}
			}
		}
		return null;
	}

	public V put(K key,V value){
		this.call.put(key,value);
		return put(key,value,0);
	}

	public V put(K key,V value,long time){
		if(key == null)
			return putForNullKey(value);
		int hash = hash(key.hashCode());
		int i = indexFor(hash,table.length);
		for(Entry<K,V> e = table[i];e != null;e = e.next){
			Object k;
			if(e.hash == hash && ((k = e.key) == key || key.equals(k))){
				V oldValue = e.value;
				e.value = value;
				e.recordAccess(this);
				return e.check() ? oldValue : null;
			}
		}
		addEntry(hash,key,value,i,time);
		return null;
	}

	private V putForNullKey(V value){
		return putForNullKey(value,0);
	}

	private V putForNullKey(V value,long time){
		for(Entry<K,V> e = table[0];e != null;e = e.next){
			if(e.key == null){
				V oldValue = e.value;
				e.value = value;
				e.recordAccess(this);
				return e.check() ? oldValue : null;
			}
		}
		addEntry(0,null,value,0,time);
		return null;
	}

	private void putForCreate(K key,V value,long time){
		int hash = (key == null) ? 0 : hash(key.hashCode());
		int i = indexFor(hash,table.length);
		for(Entry<K,V> e = table[i];e != null;e = e.next){
			Object k;
			if(e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))){
				e.setValue(value);
				return;
			}
		}
		createEntry(hash,key,value,i,time);
	}

	private void putAllForCreate(Map<? extends K,? extends V> m){
		if(m instanceof CacheMap){
			for(Iterator<? extends Map.Entry<? extends K,? extends V>> i = m.entrySet().iterator();i.hasNext();){
				CacheMap.Entry<? extends K,? extends V> e = (Entry<? extends K,? extends V>)i.next();
				putForCreate(e.getKey(),e.getValue(),e.checkTime);
			}
		}else{
			for(Iterator<? extends Map.Entry<? extends K,? extends V>> i = m.entrySet().iterator();i.hasNext();){
				Map.Entry<? extends K,? extends V> e = i.next();
				putForCreate(e.getKey(),e.getValue(),0);
			}
		}
	}

	void resize(int newCapacity){
		Entry<K,V>[] oldTable = table;
		int oldCapacity = oldTable.length;
		if(oldCapacity == MAXIMUM_CAPACITY){
			threshold = Integer.MAX_VALUE;
			return;
		}
		@SuppressWarnings("unchecked")
		Entry<K,V>[] newTable = new Entry[newCapacity];
		transfer(newTable);
		table = newTable;
		threshold = (int)(newCapacity * loadFactor);
	}

	void transfer(Entry<K,V>[] newTable){
		Entry<K,V>[] src = table;
		int newCapacity = newTable.length;
		for(int j = 0;j < src.length;j++){
			Entry<K,V> e = src[j];
			if(e != null){
				src[j] = null;
				do{
					Entry<K,V> next = e.next;
					int i = indexFor(e.hash,newCapacity);
					e.next = newTable[i];
					newTable[i] = e;
					e = next;
				}while(e != null);
			}
		}
	}

	public void putAll(Map<? extends K,? extends V> m){
		int numKeysToBeAdded = m.size();
		if(numKeysToBeAdded == 0)
			return;
		if(numKeysToBeAdded > threshold){
			int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
			if(targetCapacity > MAXIMUM_CAPACITY)
				targetCapacity = MAXIMUM_CAPACITY;
			int newCapacity = table.length;
			while(newCapacity < targetCapacity)
				newCapacity <<= 1;
			if(newCapacity > table.length)
				resize(newCapacity);
		}
		for(Iterator<? extends Map.Entry<? extends K,? extends V>> i = m.entrySet().iterator();i.hasNext();){
			Map.Entry<? extends K,? extends V> e = i.next();
			put(e.getKey(),e.getValue());
		}
	}

	public V remove(Object key){
		Entry<K,V> e = removeEntryForKey(key);
		return (e == null ? null : e.value);
	}

	final Entry<K,V> removeEntryForKey(Object key){
		int hash = (key == null) ? 0 : hash(key.hashCode());
		int i = indexFor(hash,table.length);
		Entry<K,V> prev = table[i];
		Entry<K,V> e = prev;
		while(e != null){
			Entry<K,V> next = e.next;
			Object k;
			if(e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))){
				if(this.call.isExpire(e)){
					size--;
					if(prev == e)
						table[i] = next;
					else
						prev.next = next;
					e.recordRemoval(this);
					return e;
				}else{
					e.recordAccess(this);
					return null;
				}
			}
			prev = e;
			e = next;
		}
		return e;
	}

	public void clear(){
		Entry<K,V>[] tab = table;
		for(int i = 0;i < tab.length;i++)
			tab[i] = null;
		size = 0;
	}

	public boolean containsValue(Object value){
		if(value == null)
			return containsNullValue();
		Entry<K,V>[] tab = table;
		for(int i = 0;i < tab.length;i++)
			for(Entry<K,V> e = tab[i];e != null;e = e.next)
				if(value.equals(e.value))
					return true;
		return false;
	}

	private boolean containsNullValue(){
		Entry<K,V>[] tab = table;
		for(int i = 0;i < tab.length;i++)
			for(Entry<K,V> e = tab[i];e != null;e = e.next)
				if(e.value == null)
					return true;
		return false;
	}

	@SuppressWarnings("unchecked")
	public Object clone(){
		CacheMap<K,V> result = null;
		try{
			result = (CacheMap<K,V>)super.clone();
		}catch(CloneNotSupportedException e){
		}
		result.table = new Entry[table.length];
		result.size = 0;
		result.init(true);
		result.putAllForCreate(this);
		return result;
	}

	static class Entry<K,V> implements Map.Entry<K,V>{
		final K key;
		V value;
		Entry<K,V> next;
		final int hash;
		private long lastAccess = 0;
		private long checkTime = 0;

		Entry(int h,K k,V v,Entry<K,V> n,long time){
			value = v;
			this.checkTime = time;
			next = n;
			key = k;
			hash = h;
			recordAccess(null);
		}

		public final K getKey(){
			return key;
		}

		public final V getValue(){
			return value;
		}

		public final V setValue(V newValue){
			V oldValue = value;
			value = newValue;
			return oldValue;
		}

		public boolean check(){
			return checkTime == 0 || System.currentTimeMillis() < checkTime + lastAccess;
		}

		@SuppressWarnings({"rawtypes","unchecked"})
		public final boolean equals(Object o){
			if(!(o instanceof Map.Entry))
				return false;
			Map.Entry<K,V> e = (Map.Entry)o;
			K k1 = getKey();
			K k2 = (K)e.getKey();
			if(k1 == k2 || (k1 != null && k1.equals(k2))){
				Object v1 = getValue();
				Object v2 = e.getValue();
				if(v1 == v2 || (v1 != null && v1.equals(v2)))
					return check();
			}
			return false;
		}

		public final int hashCode(){
			return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
		}

		public final String toString(){
			return getKey().toString().concat("=").concat(getValue().toString());
		}

		void recordAccess(CacheMap<K,V> m){
			if(checkTime > 0){
				lastAccess = System.currentTimeMillis();
			}
			if(null != m){
				m.vallValue(this);
			}
		}

		void recordRemoval(CacheMap<K,V> m){
			m.removeValue(this);
		}
	}

	void addEntry(int hash,K key,V value,int bucketIndex,long time){
		Entry<K,V> e = table[bucketIndex];
		table[bucketIndex] = new Entry<K,V>(hash,key,value,e,time);
		if(size++ >= threshold)
			resize(2 * table.length);
	}

	void createEntry(int hash,K key,V value,int bucketIndex,long time){
		Entry<K,V> e = table[bucketIndex];
		table[bucketIndex] = new Entry<K,V>(hash,key,value,e,time);
		size++;
	}

	public Set<K> keySet(){
		if(size > 0){
			Set<K> s = new HashSet<K>(size);
			for(Entry<K,V> t:table){
				if(null != t && t.check()){
					s.add(t.key);
				}
			}
			return s;
		}
		return null;
	}

	public Collection<V> values(){
		if(size > 0){
			Collection<V> s = new ArrayList<V>(size);
			for(Entry<K,V> t:table){
				if(null != t && t.check()){
					s.add(t.value);
				}
			}
			return s;
		}
		return null;
	}

	private void writeObject(java.io.ObjectOutputStream s) throws IOException{
		s.defaultWriteObject();
		s.writeInt(table.length);
		s.writeInt(size);
		if(size > 0){
			for(Entry<K,V> t:table){
				if(null != t && t.check()){
					s.writeObject(t.getKey());
					s.writeObject(t.getValue());
					s.writeLong(t.checkTime);
					s.writeLong(t.lastAccess);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void readObject(java.io.ObjectInputStream s) throws IOException,ClassNotFoundException{
		s.defaultReadObject();
		int numBuckets = s.readInt();
		table = new Entry[numBuckets];
		init(true);
		int size = s.readInt();
		for(int i = 0;i < size;i++){
			K key = (K)s.readObject();
			V value = (V)s.readObject();
			long checkTime = s.readLong();
			long lastAccess = s.readLong();
			if(checkTime == 0 || System.currentTimeMillis() < checkTime + lastAccess){
				putForCreate(key,value,checkTime);
			}
		}
	}

	int capacity(){
		return table.length;
	}

	float loadFactor(){
		return loadFactor;
	}

	@Override
	public Set<java.util.Map.Entry<K,V>> entrySet(){
		if(size > 0){
			Set<java.util.Map.Entry<K,V>> s = new HashSet<java.util.Map.Entry<K,V>>(size);
			for(Entry<K,V> t:table){
				if(null != t && t.check()){
					s.add(t);
				}
			}
			return s;
		}
		return null;
	}

	public void setCall(CacheEvent<K,V> call){
		this.call = call;
	}

	@Override
	protected void finalize() throws Throwable{
		super.finalize();
		stopRefresh();
	}

	protected void vallValue(Entry<K,V> entry){
	}

	protected void removeValue(Entry<K,V> entry){
		this.call.remove(entry.value);
	}
}
